const mongoose = require('../utils/db')

const goodCartSchema = new mongoose.Schema({
    phone: String,
    goods_id: String,
    goods_count: Number,
    car_size: String
})
var Goodscart = mongoose.model('shop_cars', goodCartSchema)


//新增一个购物车
const addGoodsCart = (goodcartinfo) => {
    const goodcart = new Goodscart(goodcartinfo)
    return new Promise((resolve, reject) => {
        goodcart.save((err, doc) => {
            if (err) reject(err)
            else resolve(doc)
        })
    })
}

//修改一个购物车
const updateGoods = (old_goodcartinfo, new_goodcartinfo) => {
    const { goods_count, car_size } = new_goodcartinfo
    new_goodcartinfo = { $set: { goods_count, car_size } }
    return new Promise((resolve, reject) => {
        Goodscart.updateOne(old_goodcartinfo, new_goodcartinfo, (err, doc) => {
            if (err) reject(err)
            else resolve(doc)
        })
    })
}

// 查找购物车
const isCartExist = (cartinfo) => {
    return new Promise((resolve, reject) => {
        Goodscart.find(cartinfo, (err, docs) => {
            if (err) {
                reject(err)
            } else {
                resolve({ isExist: docs.length > 0, goodinfo: docs[0] })
            }
        })
    })

}

//查询一个用户的购物车
const getUserGoods = (phone) => {
        return new Promise((resolve, reject) => {
            Goodscart.find(phone, (err, docs) => {
                if (err) {
                    reject(err)
                } else {
                    resolve({ isExist: docs.length > 0, docs })
                }
            })
        })
    }
    //删除一个购物车
const delGoodsCart = (cartinfo) => {
    return new Promise((resolve, reject) => {
        Goodscart.deleteOne(cartinfo, (err, docs) => {
            console.log(cartinfo, '+++++++++++++++++++');

            if (err) {
                reject(err)
            } else {
                resolve({ isExist: docs.length > 0, docs })
            }
        })
    })
}
module.exports = {
    updateGoods,
    addGoodsCart,
    isCartExist,
    getUserGoods,
    delGoodsCart
}